package com.luoqiwen.android.sinaurldecoder

import android.view.View
import android.view.View.OnClickListener
import android.widget.EditText
import android.widget.Switch
import android.widget.Toast
import com.google.android.material.textfield.TextInputEditText
import com.squareup.okhttp.HttpUrl
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

class ExecuteBtnListener(private val main: MainActivity) : OnClickListener {
    private val input = main.findViewById<TextInputEditText>(R.id.inputBox)
    private val secondaryDecode = main.findViewById<Switch>(R.id.secondaryDecode)
    private val secondaryDecodeDepth = main.findViewById<EditText>(R.id.secondaryDecodeDepth)

    override fun onClick(v: View?) {
        MainScope().launch(Dispatchers.Main) {
            main.debug("Button click event detected. Now executing url decode task...")
            val url = input.text?.toString()
            if (input.text.isNullOrEmpty() || url == null || url == "") {
                Toast.makeText(main.applicationContext, "还没有输入url呢", Toast.LENGTH_SHORT).show()
                return@launch
            }
            main.debug("Current box state: content='$url'")

            val sd = secondaryDecode.isChecked
            val sdd = if (sd) secondaryDecodeDepth.text?.toString()?.toInt() ?: 1 else 1
            main.debug("Task args: {url=$url, sd=$sd, sdd=$sdd}")

            val result = URLDecoder.decode(url, sd ,sdd)
            //main.applicationContext.asy
            var result0 : HttpUrl? = null
            main.debug("转换结果:")
            main.debug("key - value")
            result.forEach { (key, list) ->
                if (list.isNotEmpty())
                    result0 = list.first()
                main.debug("$key - $list")
            }

            if (result0 != null)
                main.findViewById<EditText>(R.id.decodeResult).setText(result0.toString())

        }
    }
}